const RequestHttps = require("../utils/request_https.js");
const Config = require("./project_config.js");
const PromiseExtends = require("../utils/promise_extends.js");
const Log = require("../utils/core_log.js");
const Tool = require("../utils/tool.js");
const Url = require("../utils/url.js");
const Login = require("../utils/privacy_login.js");

const Hostname = Config.Hostname;
const Port = Config.Port;

function request(_promise, _success, _fail) {
  const logCallerName = request.name;
  _promise
    .then(function (res) {
      const data = res.data;
      if (data.type == 'Data') {
        _success(data.data, res);
      } else if (data.type == 'Validate') {
        Tool.showInfo(data.data.object);
      } else {
        Log.error(logCallerName, res)
        Tool.showInfo('返回结果错误');
      }
    })
    .catch(function (res) {
      if (res instanceof Error) {
        console.error(res)
        return;
      }
      _fail ? _fail(res) : Tool.showInfo(res.errorMessage);
    })
    .finally(function () {
      Tool.hideLoading();
    });
}

function getRequest(_path, _success, _fail) {
  Tool.showLoading();
  request(
    RequestHttps.getRequest(Hostname, Port, warpPath(_path)),
    _success,
    _fail
  );    
}

function postRequest(_path, _data, _success, _fail) {
  Tool.showLoading();
  request(
    RequestHttps.postRequest(Hostname, Port, warpPath(_path), _data),
    _success,
    _fail
  );
}

function putRequest(_path, _data, _success, _fail) {
  Tool.showLoading();
  request(
    RequestHttps.putRequest(Hostname, Port, warpPath(_path), _data),
    _success,
    _fail
  );
}

function deleteRequest(_path, _success, _fail) {
  Tool.showLoading();
  request(
    RequestHttps.deleteRequest(Hostname, Port, warpPath(_path)),
    _success,
    _fail
  );
}

/**
 * 处理 ptah, const url_isLogin = Service + "wx/isLogin?skey=" + skey;
 */
function warpPath(path) {
  const URL = Url.newInstance(path);
  const skey = Login.getLoginSkey();
  if (skey) {
    URL.setPara('skey', skey)
  }
  return URL.get();
}

module.exports = {
  warpPath: warpPath,
  getRequest: getRequest,
  postRequest: postRequest,
  putRequest: putRequest,
  deleteRequest: deleteRequest
};